package com.javacoo.xservice.base.support.handler.internal;

import java.util.Optional;
import java.util.function.BiFunction;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import com.javacoo.xservice.base.BaseResponse;
import com.javacoo.xservice.base.bean.SecurityBean;
import com.javacoo.xservice.base.security.util.SecurityUtil;
import com.javacoo.xservice.base.support.handler.config.EncodeConfig;
import com.javacoo.xservice.base.support.swaparea.SwapAreaUtils;
import com.javacoo.xservice.base.utils.FastJsonUtil;

/**
 * 编码处理器
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年7月12日上午9:54:18
 */
@Component
@ConditionalOnBean(EncodeConfig.class)
public class EnCodeHandler extends AbstractHandler {
	/**编码配置*/
	@Autowired
	private EncodeConfig encodeConfig;
	@Override
	public void afterHandle(Object input) {
		if(!(input instanceof BaseResponse)){
			return;
		}
		if(!checkConfig(encodeConfig.getEncodeParamMap())){
			return;
		}
		BaseResponse rsp = (BaseResponse)input;
        String appKey = SwapAreaUtils.getSwapAreaData().getBaseRequest().getAppKey();
        //签名
        SecurityBean securityBean = appCoreSetting.getSecurityMap().get(appKey);
        if(StringUtils.isBlank(securityBean.getSecretKey())){
            return;
        }
        String els = encodeConfig.getEncodeParamMap().get(SwapAreaUtils.getSwapAreaData().getReqMethod());
        rsp.getData()
            .map(o->translate(els,o,securityBean.getSecretKey(),encodeFunction))
            .ifPresent(m->rsp.setData(FastJsonUtil.toBean(FastJsonUtil.collectToString(m.get()))));
	}
    /**
     * 索引
     * <li>自然排序</li>
     *
     * @author duanyong@jccfc.com
     * @date 2021/3/4 11:06
     * @return: int
     */
    @Override
    public int index() {
        return 2;
    }
	/**
	 * 编码函数
	 * @param s 待编码值
	 * @return 编码后的值
	 */
	private BiFunction<String,String,Optional<String>> encodeFunction = (s,key)-> Optional.ofNullable(SecurityUtil.encryptDes(s,key));
}
